import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import { ProjectTag } from '@entity/project';

@Component
export class TagSelector extends Vue {

    /** 人数限制 */
    @Prop({
        default: 1
    })
    private memberLimit: number;

    /** 所有职位的集合 */
    @Prop({
        default: () =>[]
    })
    private positions : Array<ProjectTag>;

    /** 是否显示此对话框 */
    @Prop({
        default: false
    })
    private display : boolean;

    /** 是单选还是组选 */
    @Prop({
        default: 'SINGLE'
    })
    private mode: 'SINGLE' | 'GROUP';

    /** 已选内容 */
    private select: Array<ProjectTag> = [];

    /** 关键字 */
    private keyword: string = '';

    /**
     * 在 keyword 发生变化时, 更新可选项
     */
    private get selections(): Array<ProjectTag> {
        if (this.keyword.isEmpty()) {
            return this.positions;
        }
        let selections: Array<ProjectTag> = [];
        this.positions.forEach((item: ProjectTag) => {
            if (item.tag.contain(this.keyword)) {
                selections.push(item);
            }
        })
        return selections;
    }

    /**
     * 在 select 发生变化时被调用, 动态将已选内容传给父组件
     */
    @Watch('select')
    private onSelectChange(val: Array<ProjectTag>, oldVal: Array<ProjectTag>): void {
        this.$emit('on-selection-change', {
            mode: this.mode,
            list: val
        });
    }

    /**
     * 向已选数组里添加元素
     * 添加过程受到人员、模式等限制
     */
    private selectPush(item: ProjectTag): void {
        if (this.mode === 'GROUP') {
            if (this.select.length < this.memberLimit) {
                this.select.push(item);
            } else {
                '已达到最大成员数量'.notifyWarn();
            }
        } else {
            if (this.select.length == 0) {
                this.select.push(item);
            } else {
                this.select = [item];
            }
        }
    }
}